package validateur;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ValidateurXMLtoXSD {

	static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";

	static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";

	static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
	
	public boolean validationXML(String xmlFile, String xsdFile)
	{
		boolean XMLOK = true;
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setIgnoringComments(true);
		dbf.setNamespaceAware(true);
		dbf.setValidating(true);
		dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
		dbf.setAttribute(JAXP_SCHEMA_SOURCE, new File(xsdFile));
		try {
			// Parsage du fichier XML avec DOM
			DocumentBuilder db = dbf.newDocumentBuilder();
			db.setErrorHandler(new ErrorHandler() {
				public void fatalError(SAXParseException e) {
					System.out
							.println("Erreur de validation XSD - Erreur fatal"+e);
				}

				public void error(SAXParseException e) {
					System.out.println("Erreur de validation XSD - Erreur"+e);
				}

				public void warning(SAXParseException e) {
					System.out.println("Erreur de validation XSD - Warning"+e);
				}
			});
			Document doc = db.parse(xmlFile);
		} catch (ParserConfigurationException pcee) {
			System.out.println(pcee);
			XMLOK = false;
		} catch (IOException ioe) {
			System.out.println(ioe);
			XMLOK = false;
		} catch (SAXException saxe) {
			System.out.println(saxe);
			XMLOK = false;
		}
		return XMLOK;
	}

}
